<template>
  <span>
    <el-switch v-bind="$attrs" v-if="switchValue" :active-text="ActiveDesc" :inactive-text="InactiveDesc" inline-prompt :loading="loading" :disabled="disabled || loading" :model-value="true" @click="ChangeSwitchValue(false)" :active-value="true" :inactive-value="false"/>
    <el-switch v-bind="$attrs" style="--el-switch-off-color: #ff0000" v-else :active-text="ActiveDesc" :inactive-text="InactiveDesc" inline-prompt :loading="loading" :disabled="disabled || loading" :model-value="false" @click="ChangeSwitchValue(true)" :active-value="true" :inactive-value="false"/>
  </span>
</template>
<script lang="ts">
import {ref, computed, ComputedRef, watch, defineComponent} from "vue";

type SwitchValue = boolean | 0 | 1 | '0' | '1';

export default defineComponent({
  emits: {
    "change": (value: SwitchValue) => true,
    "input": (value: SwitchValue) => true,
    "update:modelValue": (value: SwitchValue) => true
  },
  props: {
    modelValue: {
      type: [String, Boolean, Number],
      defalut: false
    },
    disabled: {
      type: Boolean,
      defalut: false
    },
    activeText: {
      type: String//ON
    },
    inactiveText: {//OFF
      type: String
    }
  },
  setup(props, {emit}) {
    const loading = ref(false)

    const ActiveDesc = computed(() => props.activeText ? props.activeText : 'ON')
    const InactiveDesc = computed(() => props.inactiveText ? props.inactiveText : 'OFF')

    watch(() => props.modelValue, (val) => {
      loading.value = false
    })

    /**
     * 选中值
     */
    const switchValue: ComputedRef<SwitchValue> = computed(() => {
      let val = props.modelValue
      return val === true || val === 'true' || val === 1 || val === '1'
    })


    /**
     * 切换表单值
     * @param val
     * @constructor
     */
    function ChangeSwitchValue(val: boolean) {
      if (props.disabled || loading.value === true) {
        return;
      }
      if (val) {
        if (props.modelValue === 'false' || props.modelValue === false) {
          ValueChange(true)
        } else if (props.modelValue === '0' || props.modelValue === 0) {
          ValueChange(1)
        }
      } else {
        if (props.modelValue === '1' || props.modelValue === 1) {
          ValueChange(0)
        } else if (props.modelValue === 'true' || props.modelValue) {
          ValueChange(false)
        }
      }
    }

    /**
     * 更改数据
     * @param value
     * @constructor
     */
    function ValueChange(value: SwitchValue) {
      emit('change', value)
      emit('input', value)
      emit('update:modelValue', value)
      loading.value = true
      setTimeout(() => loading.value = false, 1000)
    }

    return {
      loading,
      switchValue,
      ChangeSwitchValue,
      ActiveDesc,
      InactiveDesc
    }
  }
})
</script>
